State Machine in C 您所在的位置:网站首页 c state State Machine in C

State Machine in C

2023-03-20 23:01| 来源: 网络整理| 查看: 265

an Overview of State MachineUse Function Pointers to Create a State MachineUse Switch Statement to Create a State Machine

This article demonstrates the state machine’s implementation in the C programming language.

an Overview of State Machine

Using a state machine to implement code is a valuable design strategy to resolve complex engineering issues. State machines take the overall design and split it into stages, referred to as states inside the state-machine jargon.

Every state is responsible for carrying out a particular function. On the other side, events are the stimuli that cause the state machine to change between states. It is also referred to as a transition.

When first written, most systems are straightforward and well-organized, but when new features are added, additional flags and variables are created to keep track of events’ history.

Then, if and else statements are added to test the ever-more-complex logical expressions created out of the many variables and flags.

In this regard, the state machines are of assistance. When utilized appropriately, state machines simplify the conditions tested at each branching point and make it easier to switch between various modes of program execution.

It turns out that the behaviour of most real-time systems can be divided into a relatively small number of non-overlapping chunks (states).

The event responses within each chunk depend only on the current event, and they no longer rely on the sequence of events that have occurred in the past.

Use Function Pointers to Create a State Machine

The following is an example of code to build a state machine in C. This specific example generates two states switches back and forth between them ten times.

Then, it displays the index number and the state corresponding to that index.

#include struct state; typedef void state_fn(struct state *); struct state { state_fn * next; int i; }; state_fn off_state, on_state; void off_state(struct state * state) { printf("%s %i\n", __func__, ++state->i); state->next = on_state; } void on_state(struct state * state) { printf("%s %i\n", __func__, ++state->i); state->next = state->i


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有